package com.hmdp.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.UserDTO;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
@Order(0)
public class FirstInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //在过滤器进行token的存活时间刷新，该拦截器拦截一切来自外部的请求
        //TODO:1.获取token
        String token = request.getHeader("authorization");
        if (StrUtil.isBlank(token)){
            return true;
        }
        //TODO:2.根据token去redis中查询uerdto是否存在--->返回一个map
        Map userDtoMap = redisTemplate.opsForHash().entries("user_Login_token" + token);
        if (userDtoMap.isEmpty()){
            return true;
        }
        //TODO:3.将这个map封装成userdto对象，存入threadlocal中
        UserDTO userDTO = new UserDTO();
        String id_first = (String) userDtoMap.get("id");
        Long id = Long.valueOf(id_first);
        String nickName =(String) userDtoMap.get("nickName");
        String icon = (String) userDtoMap.get("icon");
        userDTO.setId(id);
        userDTO.setNickName(nickName);
        UserHolder.saveUser(userDTO);
        //TODO:4.刷新token的有效时间
        redisTemplate.expire("user_Login_token" + token,10, TimeUnit.MINUTES);
        //TODO:5.放行
        return true;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //对用户的信息进行移除
        UserHolder.removeUser();
    }
}
